<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 顶部查询列表 cabinet //机柜名称-->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="机柜名称" prop="cabinet">
              <el-input
                v-model="queryParams.cabinet"
                placeholder="请输入机柜名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
                @clear="handleQuery"
              />
            </el-form-item>
            <el-form-item label="机房">
              <el-select
                v-model="queryParams.room"
                clearable
                placeholder="请选择机房"
                style="width: 200px"
                @change="handleChangeRoom"
              >
                <el-option
                  v-for="item in options.machine_rooms"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="handleResetQuery">
                <i-ep-refresh />
                重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button type="success" @click="openDialog(DialogType.ADD)"
                  ><i-ep-plus />新增</el-button
                >
                <el-button
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />批量删除</el-button
                >
              </div>
              <!-- <div>
                <el-dropdown split-button>
                  导入
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="downloadTemplate">
                        <i-ep-download />下载模板</el-dropdown-item
                      >
                      <el-dropdown-item @click="openDialog(DialogType.IMPORT)">
                        <i-ep-top />导入数据</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button class="ml-3" @click="handleExport"
                  ><template #icon><i-ep-download /></template>导出</el-button
                >
              </div> -->
            </div>
          </template>
          <!-- 展示表单 -->
          <el-table
            v-loading="loading"
            :data="pageData"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="60" align="center" />
            <el-table-column key="id" label="ID" align="center" width="60">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              label="机柜编号"
              align="center"
              prop="number"
              width="160"
            />
            <el-table-column label="状态" align="center">
              <template #default="scope">
                <el-tag
                  v-if="scope.row.status.value"
                  :type="getStatusType(scope.row)"
                  effect="dark"
                >
                  {{ scope.row.status.value }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="关联机房"
              align="center"
              prop="machine_room.name"
            />
            <el-table-column label="备注" align="center" prop="remarks" />
            <!-- <el-table-column
              label="创建时间"
              align="center"
              prop="CreatedTime"
              width="160"
            />
            <el-table-column
              label="更新时间"
              align="center"
              prop="UpdatedTime"
              width="160"
            /> -->
            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              width="200"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="openDialog(DialogType.EDIT, scope.row)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.page"
            v-model:limit="queryParams.pagesize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        v-if="isAddOrEdit || isDetail"
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="机柜编号" prop="cabinet_number">
          <el-input
            v-model="formData.cabinet_number"
            autocomplete="off"
            placeholder="请输入机柜名称"
            :disabled="isDetail"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="formData.status"
            clearable
            placeholder="请选择状态"
            :disabled="isDetail"
            style="width: 200px"
          >
            <el-option
              v-for="item in options.status"
              :key="item.id"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="机房">
          <el-select
            v-model="formData.room"
            clearable
            placeholder="请选择机房"
            :disabled="isDetail"
            style="width: 700px"
            @change="handleChangeRoom"
          >
            <el-option
              v-for="item in options.machine_rooms"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            type="textarea"
            v-model="formData.remarks"
            autocomplete="off"
            placeholder="备注"
            :disabled="isDetail"
          />
        </el-form-item>
      </el-form>

      <!-- 用户导入表单 -->
      <!-- <el-form
        ref="userFormRef"
        v-else-if="isImport"
        :model="importData"
        label-width="100px"
      >
        <el-form-item label="Excel文件">
          <el-upload
            ref="uploadRef"
            action=""
            drag
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :limit="1"
            :auto-upload="false"
            :file-list="importData.fileList"
            :on-change="handleFileChange"
            :on-exceed="handleFileExceed"
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div>xls/xlsx files</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form> -->

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!isDetail" type="primary" @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// defineOptions({
//   name: "PhoneManage",
//   inheritAttrs: false,
// });

// const statuOptions = reactive([
//   { id: 1, label: "正常", value: "1" },
//   { id: 2, label: "停用", value: "2" },
// ]);

import CMDB_CabinetAPI from "@/api/cmdb/cabinet";

import {
  CabinetForm,
  CabinetQuery,
  CabinetPageVO,
} from "@/api/cmdb/cabinet/model";
import type { UploadInstance, TableColumnCtx } from "element-plus";
import { genFileId } from "element-plus";
import { DialogType } from "@/enums/DialogType";
import { number } from "echarts";

const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<CabinetPageVO>({
  page: 1,
  pagesize: 10,
});
const dateTimeRange = ref("");
const total = ref(0); // 数据总数
const pageData = ref<CabinetPageVO[]>(); // 用户分页数据

const options = ref({
  status: [] as any[],
  machine_rooms: [] as any[],
});
function getStatusType(row: any) {
  switch (row.status.id) {
    case 1:
      return "success";
    case 2:
      return "primary";
    case 3:
      return "danger";
    default:
      return "danger";
  }
}

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "number-form",
  width: 800,
  title: "",
});

// 用户表单数据
const formData = reactive<CabinetForm>({
  status: "",
  room: "",
});

// 用户导入数据
const importData = reactive({
  // deptId: undefined,
  file: undefined,
  fileList: [],
});

// 校验规则
const rules = reactive({
  // username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  // name: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  // password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
  // deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  // roleIds: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  // email: [
  //   {
  //     pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
  //     message: "请输入正确的邮箱地址",
  //     trigger: "blur",
  //   },
  // ],
  phone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

const machine_rooms = ref<any[]>([]);
/** 查询 */
function handleQuery() {
  loading.value = true;
  CMDB_CabinetAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.data.data;
      options.value = data.data.options; //获取对象属性
      total.value = data.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleChangeRoom(value: number) {
  formData.room = "";
  options.value.machine_rooms = machine_rooms.value.filter((item) => {
    return item.room.id == value;
  });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.room = undefined;
  dateTimeRange.value = "";
  queryParams.page = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

const isAddOrEdit = computed(() => {
  return dialog.type === DialogType.ADD || dialog.type === DialogType.EDIT;
});
const isDetail = computed(() => {
  return dialog.type === DialogType.DETAIL;
});

const isImport = computed(() => {
  return dialog.type === DialogType.IMPORT;
});

//选择关联机柜
/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 * @param id 用户ID
 */
async function openDialog(type: string, row?: any) {
  dialog.visible = true;
  dialog.type = type;
  switch (dialog.type) {
    case DialogType.ADD:
      dialog.title = "新增";
      Object.assign(formData, {
        cabinet_number: "",
        status: "",
        room: "",
      });
      break;
    case DialogType.EDIT:
      dialog.title = "修改";
      const response = await CMDB_CabinetAPI.getById(row.id);
      const rowData = response.data;
      // console.log(rowData);
      Object.assign(formData, { ...rowData });

      break;
    case DialogType.IMPORT:
      // 用户导入弹窗
      dialog.title = "导入";
      dialog.width = 600;
      break;
    case DialogType.DETAIL:
      dialog.title = "查看";
      Object.assign(formData, { ...row });
      formData.status = row?.status?.id; //当前状态
      formData.room = row?.machine_room?.id; // 机房
      break;

    default:
      break;
  }
}
/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  if (isAddOrEdit.value) {
    userFormRef.value.resetFields();
    userFormRef.value.clearValidate();

    // formData.id = 0;
    // formData.status = 1;
  } else if (isImport.value) {
    importData.file = undefined;
    importData.fileList = [];
  }
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  if (dialog.type === DialogType.IMPORT) {
    // TODO 导入逻辑
  } else if (
    dialog.type === DialogType.ADD ||
    dialog.type === DialogType.EDIT
  ) {
    userFormRef.value.validate((valid: any) => {
      if (valid) {
        const userId = formData.id;
        loading.value = true;
        if (userId) {
          CMDB_CabinetAPI.update(formData)
            .then(() => {
              ElMessage.success("修改成功");
              closeDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          // console.log(formData, "formData");

          CMDB_CabinetAPI.add(formData)
            .then((res) => {
              // console.log(res, "res");

              ElMessage.success("新增成功");
              closeDialog();
              handleResetQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  }
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    CMDB_CabinetAPI.deleteByIds(userIds).then(() => {
      ElMessage.success("删除成功");
      handleResetQuery();
    });
  });
}

/** 下载导入模板 */
// function downloadTemplate() {
//   Ap1API.downloadTemplate().then((response: any) => {
//     const fileData = response.data;
//     const fileName = decodeURI(
//       response.headers["content-disposition"].split(";")[1].split("=")[1]
//     );
//     const fileType =
//       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

//     const blob = new Blob([fileData], { type: fileType });
//     const downloadUrl = window.URL.createObjectURL(blob);

//     const downloadLink = document.createElement("a");
//     downloadLink.href = downloadUrl;
//     downloadLink.download = fileName;

//     document.body.appendChild(downloadLink);
//     downloadLink.click();

//     document.body.removeChild(downloadLink);
//     window.URL.revokeObjectURL(downloadUrl);
//   });
// }

/** Excel文件 Change */
// function handleFileChange(file: any) {
//   importData.file = file.raw;
// }

/** Excel文件 Exceed  */
// function handleFileExceed(files: any) {
//   uploadRef.value!.clearFiles();
//   const file = files[0];
//   file.uid = genFileId();
//   uploadRef.value!.handleStart(file);
//   importData.file = file;
// }

/** 导出用户 */
// function handleExport() {
//   Ap1API.export(queryParams).then((response: any) => {
//     const fileData = response.data;
//     const fileName = decodeURI(
//       response.headers["content-disposition"].split(";")[1].split("=")[1]
//     );
//     const fileType =
//       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

//     const blob = new Blob([fileData], { type: fileType });
//     const downloadUrl = window.URL.createObjectURL(blob);

//     const downloadLink = document.createElement("a");
//     downloadLink.href = downloadUrl;
//     downloadLink.download = fileName;

//     document.body.appendChild(downloadLink);
//     downloadLink.click();

//     document.body.removeChild(downloadLink);
//     window.URL.revokeObjectURL(downloadUrl);
//   });
// }

onMounted(() => {
  handleQuery();
});
</script>
